<template>
<div class="main">
  <div class="context">
    <canvas id="signature" ref="canvasDom" width="1300" height="500"></canvas>
  </div>
  <div class="tools">
    <div @click="clear">清空</div>
    <div @click="back">回退</div>
    <div @click="download">下载</div>
  </div>
</div>
</template>

<script setup lang="ts">
import {ref,reactive,onMounted } from "vue";
import * as url from "url";

const canvasDom = ref(null)
const state = reactive({
  mouseState:false,
  signature:undefined,
  imgDataList:[]
})
onMounted(()=>{
  canvasDom.value.addEventListener('mousedown',mouseDownHandle)
  canvasDom.value.addEventListener('mouseup',mouseUpHandle)
  canvasDom.value.addEventListener('mousemove',moveHandle)
  const signature = canvasDom.value.getContext('2d')
  signature.lineWidth = 8;
  signature.strokeStyle = '#fff';
  signature.lineCap = 'round'
  signature.lineJoin = "round";
  state.signature = signature
})

const mouseDownHandle = (e)=>{
  state.mouseState = true
  state.signature.beginPath()
  state.signature.moveTo(e.offsetX, e.offsetY)
  const imgData = state.signature.getImageData(0,0,1300,500)
  state.imgDataList.push(imgData)
}

const clear = ()=>{
  state.signature.clearRect(0, 0, 1300, 500)
  state.imgDataList = []
}
const back = ()=>{
  if(state.imgDataList.length == 0) return
  state.signature.putImageData(state.imgDataList.pop(), 0, 0);
}
const download = ()=>{
  canvasDom.value.toBlob((blob)=>{
    const a = document.createElement('a')
    document.body.appendChild(a)
    a.download = '签名.png'
    const bolblist = [blob]
    a.href = URL.createObjectURL(new Blob(bolblist))
    a.click()
    a.remove()
  })
}

const mouseUpHandle = ()=>{
  state.mouseState = false
}

const moveHandle = (event)=>{
  if(state.mouseState){
    state.signature.lineTo(event.offsetX, event.offsetY)
    state.signature.stroke()
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */
.main{
  width: 100%;
  height: 700px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-top:80px;
  .context{
    flex: 1;
    background: url(../../assets/imgs/bg1.png) no-repeat;
    width: 1300px;
    background-size: 100% 100%;
    position: relative;
    padding-top:120px;
    #signature{
      width: 1300px;
      height: 500px;
    }
  }
  .context::after{
    content: "写字板";
    position: absolute;
    top: 33px;
    font-size: 50px;
    color: white;
    left: 50%;
    transform: translateX(-50%);
  }
  .tools{
    height: 80px;
    display: flex;
    justify-content: center;
    >div{;
      margin: 10px 20px;
      padding: 5px 20px;
      border: 1px solid dodgerblue;
      border-radius: 4px;
      color: white;
      font-size: 22px;
      line-height: 50px;
      cursor: pointer;
    }
  }
}
</style>